package com.zephyr.io.chatroom;

import java.io.*;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ClientHandler extends Thread {

    public static final String REGISTER = "[register]";
    private static final Map<String, Socket> SOCKET_MAP = new ConcurrentHashMap<>();

    private final Socket client;
    private String name;

    public ClientHandler(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try {
            //获取客户端输入流
            InputStream in = this.client.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while (!client.isClosed() && (line = reader.readLine()) != null) {
                if (line.equalsIgnoreCase("bye")) {
                    break;
                }
                if (line.startsWith(REGISTER)) {
                    register(line.replace(REGISTER, ""));
                } else {
                    groupChat(line, false);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            quit();
        }
    }

    private void register(String name) {
        this.name = name;
        SOCKET_MAP.put(name, this.client);
        System.out.println(name + "上线了");
        groupChat(name + "上线了", true);
        printOnlineClient();
    }

    private void groupChat(String message, boolean isSystem) {
        if (!isSystem) {
            message = this.name + "说：" + message;
        }
        for (Map.Entry<String, Socket> entry : SOCKET_MAP.entrySet()) {
            Socket socket = entry.getValue();
            if (socket == this.client) {
                continue;
            }
            sendMessage(socket, message);
        }
    }

    private void quit() {
        SOCKET_MAP.remove(this.name);
        System.out.println(this.name + "下线了");
        groupChat(this.name + "下线了", true);
        printOnlineClient();
    }

    //打印当前在线客户人数
    private void printOnlineClient() {
        System.out.println("当前在线的客户端有：" + SOCKET_MAP.size() + "个，名称列表如下：");
        for (String name : SOCKET_MAP.keySet()) {
            System.out.println(name);
        }
    }

    //发指定消息到客户端
    private void sendMessage(Socket client, String msg) {
        try {
            OutputStream out = client.getOutputStream();
            PrintStream printStream = new PrintStream(out);
            printStream.println(msg);
            printStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
